package com.foreknow.elm.controller;

import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.service.impl.CartServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

public class CartController {
    /**
     * 根据用户编号查询此用户所有购物车信息
     * 根据用户编号和商家编号，查询此用户购物车中某个商家的所有购物车信息
     * @param req
     * @return
     * @throws Exception
     */
    public List<Cart> listCart(HttpServletRequest req) throws Exception{
        List<Cart> list = new ArrayList<>();
        CartService service = new CartServiceImpl();
        String userId = req.getParameter("userId");
        try {
            int businessId = Integer.parseInt(req.getParameter("businessId"));
            list = service.listCart(userId,businessId);
        } catch (Exception e){
            list = service.listCart(userId);
        }
        return list;
    }

    /**
     * 向购物车表中添加一条记录
     * @param req
     * @return
     * @throws Exception
     */
    public int saveCart(HttpServletRequest req) throws Exception{
        String userId = req.getParameter("userId");
        int businessId = Integer.parseInt(req.getParameter("businessId"));
        int foodId = Integer.parseInt(req.getParameter("foodId"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        cart.setFoodId(foodId);
        cart.setQuantity(quantity);
        CartService service = new CartServiceImpl();
        int result = service.saveCart(cart);
        return result;
    }

    /**
     * 根据用户编号、商家编号、食品编号更新数量
     * @param req
     * @return
     * @throws Exception
     */
    public int updateCart(HttpServletRequest req) throws Exception{
        String userId = req.getParameter("userId");
        int businessId = Integer.parseInt(req.getParameter("businessId"));
        int foodId = Integer.parseInt(req.getParameter("foodId"));
        int quantity = Integer.parseInt(req.getParameter("quantity"));
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        cart.setFoodId(foodId);
        cart.setQuantity(quantity);
        CartService service = new CartServiceImpl();
        int result = service.updateCart(cart);
        return result;
    }

    public int removeCart(HttpServletRequest req) throws Exception{
        CartService service = new CartServiceImpl();
        int result = 0;
        String userId = req.getParameter("userId");
        int businessId = Integer.parseInt(req.getParameter("businessId"));
        try {
            int foodId = Integer.parseInt(req.getParameter("foodId"));
            result = service.removeCart(userId,businessId,foodId);
        } catch (Exception e){
            result = service.removeCart(userId,businessId);
        }
        return result;
    }
}
